package tk.mybatis.springboot.share.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import net.sf.json.JSONObject;
import tk.mybatis.mapper.util.StringUtil;

public class WechatJsSdkUtil {
	private static Logger logger = Logger.getLogger(WechatJsSdkUtil.class);
	/** 得到微信js—sdk的调用权限 */
	public static String getJsapi_ticket() {
		//先从缓存中取找，如果是有，直接用缓存中的值
		String jsapi_ticket = (String) RedisUtils.getStr(WechatUtil.cache_jsapi_ticket);
		if (StringUtil.isNotEmpty(jsapi_ticket)) {
			//如果是有，则直接返回，否则去微信取值
			return jsapi_ticket;
		}

		Map<String, String> t_map = new HashMap<>();
		//		String access_token_openid = WechatJsSdkUtil.getAccess_token_openid(code);
		//
		//		String access_token = access_token_openid.split("&")[0];
		//		String openid = access_token_openid.split("&")[1];
		//固定
		t_map.put("access_token", WechatUtil.getAccess_token());
		t_map.put("type", "jsapi");

		String str = HttpUtil.sendGet(WechatUtil.url + "/cgi-bin/ticket/getticket", t_map);
		System.out.println(str);
		//返回的对象
		JSONObject json = JSONObject.fromObject(str);

		//判断是否存在
		jsapi_ticket = (String) json.get("ticket");
		if (StringUtil.isNotEmpty(jsapi_ticket)) {
			int expires_in = json.getInt("expires_in");
			logger.info("成功获取到jsapi_ticket：" + jsapi_ticket + "，时间为" + expires_in + "秒");
			//保存到缓存中取
			RedisUtils.setStr(WechatUtil.cache_jsapi_ticket, jsapi_ticket, expires_in);
		} else {
			logger.info("未获取到微信的jsapi_ticket");
			return null;
		}

		return jsapi_ticket;
	}

	/**
	 * 根据刷新凭证得到 openid&access_token，如果是 刷新凭证为空，或者是返回空，则必须重新授权
	 * @param refresh_token
	 * @return
	 */
	public static String getOpenId_refresh_token(final String refresh_token) {
		if (StringUtil.isEmpty(refresh_token)) {
			return null;
		}

		String access_token_refresh_token = (String) RedisUtils.getStr(refresh_token);
		if (StringUtil.isNotEmpty(access_token_refresh_token)) {
			//如果是有，则直接返回，否则去微信取值
			return access_token_refresh_token;
		}

		//重新刷新一下，如果是刷新失败，则返回空，空则需要重新授权了
		access_token_refresh_token = refresh_token(refresh_token);
		return access_token_refresh_token;
	}

	/**
	 * 根据js_code，将数据存入缓存
	 * @param code js_code
	 * @return openid&access_token
	 */
	public static String saveToken(final String code) {
		if (StringUtil.isEmpty(code)) {
			return null;
		}
		String refresh_token = "";

		Map<String, String> t_map = new HashMap<>();
		//固定
		t_map.put("appid", WechatUtil.Appid);
		t_map.put("secret", WechatUtil.AppSecret);
		t_map.put("code", code);
		t_map.put("grant_type", "authorization_code");

		String str = HttpUtil.sendPost(WechatUtil.url + "/sns/oauth2/access_token", t_map);
		System.out.println(str);
		//返回的对象
		JSONObject json = JSONObject.fromObject(str);

		//判断是否存在
		String access_token = (String) json.get("access_token");
		if (StringUtil.isNotEmpty(access_token)) {
			//过期时间
			int expires_in = json.getInt("expires_in");
			//用户唯一标识
			String openid = json.getString("openid");
			//token刷新凭证
			refresh_token = json.getString("refresh_token");

			String access_token_refresh_token = openid + "&" + access_token;
			logger.info("根据js_code:" + code + "成功获取到js_access_token：" + access_token + "，唯一openid:" + openid + "刷新凭证refresh_token:" + refresh_token + ",时间为" + expires_in + "秒");
			//保存到缓存中取
			RedisUtils.setStr(refresh_token, access_token_refresh_token, expires_in);
		} else {
			logger.info("未获取到微信js_access_token");
			return null;
		}
		return refresh_token;
	}

	/**
	 * 刷新用户的超时时间，
	 * @param refresh_token 刷新凭证
	 * @return openid&access_token
	 */
	public static String refresh_token(String refresh_token) {
		String access_token_refresh_token = null;

		Map<String, String> t_map = new HashMap<>();
		//固定
		t_map.put("appid", WechatUtil.Appid);
		t_map.put("grant_type", "refresh_token");
		t_map.put("refresh_token", refresh_token);

		String str = HttpUtil.sendPost(WechatUtil.url + "/sns/oauth2/refresh_token", t_map);
		System.out.println(str);

		try {
			//返回的对象
			JSONObject json = JSONObject.fromObject(str);

			//判断是否存在
			String access_token = (String) json.get("access_token");
			if (StringUtil.isNotEmpty(access_token)) {
				//过期时间
				int expires_in = json.getInt("expires_in");
				//用户唯一标识
				String openid = json.getString("openid");
				//token刷新凭证
				refresh_token = json.getString("refresh_token");
				//scope
				//			String scope = json.getString("scope");

				access_token_refresh_token = openid + "&" + access_token;
				logger.info("刷新js_access_token：" + access_token + "，唯一openid:" + openid + "刷新凭证refresh_token:" + refresh_token + ",时间为" + expires_in + "秒");
				//保存到缓存中取
				RedisUtils.setStr(refresh_token, access_token_refresh_token, expires_in);
			} else {
				logger.info("刷新js_access_token失败");
			}
		} catch (Exception e) {
			logger.info("刷新js_access_token失败", e);
		}

		return access_token_refresh_token;
	}
}
